<template>
  <div class="article-editor article-box">
    <el-dialog
      v-model="isShowTagSelectModel"
      title="选择标签"
      center
      width="30%"
      :before-close="handleClose"
    >
      <div v-for="(tagGroup, index) in showTags" :key="index">
        <h3 class="tag-group">{{ tagGroup.groupName }}</h3>
        <el-checkbox-group v-model="selectedTags" @change="tagChange">
          <el-checkbox
            v-for="tag in tagGroup.tags"
            :key="tag.id"
            :label="tag.name"
          ></el-checkbox>
        </el-checkbox-group>
      </div>
    </el-dialog>

    <div class="article-box-title">
      <span class="article-box--title-home">
        <el-button class="fs-15" @click="goHome" type="primary" size="large"
          >返回首页</el-button
        >
      </span>
      <input
        v-model="article.title"
        class="article-box-title-input"
        placeholder="这里输入文章标题"
      />
    </div>

    <mavon-editor
      class="article-box-content"
      placeholder="这里输入文章内容，markdown格式。"
      :style="{ zIndex: 0 }"
      :toolbars="editorSetting"
      v-model="article.markdownContent"
      ref="md"
      @save="updateArticle"
      @imgAdd="addImg"
    />
  </div>

  <div class="article-box-foot">
    <el-select
      v-model="article.typeId"
      class="article-box-foot-type"
      placeholder="选择所属分类"
    >
      <el-option
        v-for="type in types"
        :key="type.id"
        :value="type.id"
        :label="type.name"
      >
      </el-option>
    </el-select>

    <div class="article-box-foot-tag">
      <el-tag
        v-for="tag in article.tags"
        :key="tag.id"
        :name="tag.name"
        @close="delTag(e, tag.name)"
        closable
        :disable-transitions="false"
        >{{ tag.name }}</el-tag
      >
      <el-button type="dashed" size="small" @click="showTagSelectModel"
        >添加标签</el-button
      >
    </div>

    <div class="article-box-foot-publish">
      <el-button @click="updateArticle" type="info" size="large"
        >保存并继续编辑</el-button
      >&nbsp;&nbsp;&nbsp;&nbsp;
      <el-button @click="saveArticle" type="primary" size="large"
        >发布</el-button
      >
    </div>
  </div>
</template>
  
  <script>
import { $post, $get } from "../utils/request";
import { ElMessage } from "element-plus";
import { editedArticle } from "../store";
export default {
  data() {
    return {
      isShowTagSelectModel: false,
      containerHeight: "500px",
      types: [],
      showTags: [],
      tags: [],
      selectedTags: [],
      defaultTypeLabel: "",
      article: {
        id: null,
        title: "",
        markdownContent: "",
        tags: [],
      },
      editorSetting: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        // imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: true, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true, // 预览
      },
    };
  },
  mounted() {
    this.loadTags();
    this.loadTypes();
    this.toEdit();
  },
  methods: {
    toEdit() {
      let useArticle = editedArticle();
      if (useArticle.article.id !== "") {
        this.article = useArticle.article;
        // this.selectedTags = this.article.tags;
      }
    },
    goHome() {
      this.$router.push({ path: "/" });
      let useArticle = editedArticle();
      useArticle.reset();
    },
    showTagSelectModel() {
      this.isShowTagSelectModel = true;
    },
    tagChange(checkedNameList) {
      if (checkedNameList.length > 5) {
        ElMessage.error("标签最多选择5个");
        const selectedTagNames = [];
        for (let i = 0; i < this.article.tags.length; i++) {
          selectedTagNames.push(this.article.tags[i].name);
        }
        this.selectedTags = selectedTagNames;
        return;
      }
      const selectedTags = [];
      for (let i = 0; i < this.tags.length; i++) {
        for (let j = 0; j < checkedNameList.length; j++) {
          if (this.tags[i].name === checkedNameList[j]) {
            selectedTags.push(this.tags[i]);
          }
        }
      }
      this.article.tags = selectedTags;
    },
    updateArticle() {
      this.postArticle("更新成功", () => {});
    },
    saveArticle() {
      this.postArticle("保存成功", () => {
        this.$router.push({ path: "/" });
      });
    },
    async postArticle(message, callback) {
      let useArticle = editedArticle();
      if (!this.preCheck()) {
        return;
      }
      const headImgs = this.getHeadImgs();

      let { code, data, msg } = await $post("/article/save", {
        id: this.article.id,
        typeId: this.article.typeId,
        title: this.article.title,
        category: "ARTICLE",
        contentType: "MARKDOWN",
        markdownContent: this.article.markdownContent,
        htmlContent: this.$refs.md.d_render,
        // tags: this.article.tags,
        tagIds: this.getTagIds(),
        headImg: headImgs.length > 0 ? JSON.stringify(headImgs) : "",
      });

      console.log(data);
      if (code === 0) {
        ElMessage.error("保存失败");
        return;
      }

      this.article.id = data.id;
      //重置全局变量
      useArticle.reset();
      ElMessage.success("保存成功");
      callback();
    },
    preCheck() {
      if (!this.article.title) {
        ElMessage.error("标题不能为空");
        return false;
      }
      if (this.article.title.length > 40) {
        ElMessage.error("标题不能超过40个字符");
        return false;
      }
      if (!this.article.markdownContent) {
        ElMessage.error("内容不能为空");
        return false;
      }
      if (!this.article.typeId) {
        ElMessage.error("类别不能为空");
        return false;
      }
      if (!this.article.tags || this.article.tags.length === 0) {
        ElMessage.error("标签不能为空");
        return false;
      }
      return true;
    },
    tagChecked() {
      if (this.tags.length === 0) {
        return;
      }
      for (let i = 0; i < this.tags.length; i++) {
        for (let j = 0; j < this.article.tags.length; j++) {
          if (this.article.tags[j].id === this.tags[i].id) {
            this.selectedTags.push(this.tags[i].name);
          }
        }
      }
    },
    typeChecked() {
      if (this.types.length === 0) {
        return;
      }
      for (let i = 0; i < this.types.length; i++) {
        console.info(this.types[i].id === this.article.typeId);
        if (this.types[i].id === this.article.typeId) {
          this.defaultTypeLabel = this.types[i].name;
        }
      }
      console.info(this.defaultTypeLabel);
    },
    getTagIds() {
      const tagIds = [];
      for (let i = 0; i < this.article.tags.length; i++) {
        tagIds.push(this.article.tags[i].id);
      }
      return tagIds;
    },
    getHeadImgs() {
      const pattern = /!\[(.*?)\]\((.*?)\)/gm;
      const result = [];
      let matcher;
      while ((matcher = pattern.exec(this.article.markdownContent)) !== null) {
        result.push({
          alt: matcher[1],
          url: matcher[2],
        });
      }
      return result;
    },
    delTag(event, name) {
      for (let i = 0; i < this.article.tags.length; i++) {
        if (this.article.tags[i].name === name) {
          this.article.tags.splice(i, 1);
        }
      }
    },
    addTag() {},
    async loadTags() {
      let { code, data } = await $post("/tag/all");

      console.log(data);

      if (code === 0) {
        return;
      }
      const allTags = data;
      this.tags = data;
      const showTags = [];
      for (let i = 0; i < allTags.length; i++) {
        let hasGroup = false;
        for (let j = 0; j < showTags.length; j++) {
          if (allTags[i].groupName === showTags[j].groupName) {
            showTags[j].tags.push(allTags[i]);
            hasGroup = true;
          }
        }
        if (!hasGroup) {
          showTags.push({
            groupName: allTags[i].groupName,
            tags: [allTags[i]],
          });
        }
      }
      this.showTags = showTags;
      this.tagChecked();
    },
    async loadTypes() {
      let { code, data } = await $get("/article/type");
      console.log(data);
      if (code === 0) {
        return;
      }
      this.types = data;
      this.typeChecked();
    },
  },
};
</script>
  
  <style scoped>
.article-editor {
  height: 90vh;
}
.fs-15 {
  font-size: 15;
}
.info {
  height: 800px;
  background-color: #f3f3f2;
}
.ivu-btn-success,
.ivu-btn-info {
  padding-left: 25px;
  padding-right: 25px;
  font-weight: 400;
  padding: 0.375rem 1.37rem;
  font-size: 1rem;
  line-height: 1.5;
}
.ivu-select-selection:hover,
.ivu-checkbox-checked .ivu-checkbox-inner,
.ivu-btn-info:hover,
.ivu-btn-small:hover,
.ivu-btn-info,
.ivu-btn-primary,
.ivu-btn-success {
  border: 1px solid #28a745;
}
.ivu-btn-small:hover,
.ivu-btn-info,
.ivu-btn-text:hover {
  color: #28a745;
}
.ivu-checkbox-checked .ivu-checkbox-inner,
.ivu-btn-primary {
  background-color: #28a745;
}
.ivu-btn-info:hover {
  color: #fff;
}
.ivu-btn-small:hover,
.ivu-btn-info {
  background-color: #fff;
}
.ivu-btn-primary,
.ivu-btn-success,
.ivu-checkbox-checked .ivu-checkbox-inner,
.ivu-btn-info:hover {
  background-color: #28a745;
}
.article-box-title {
  width: 100%;
  height: 80px;
}
.article-box--title-home,
.article-box-title-input,
.article-box-foot-type,
.article-box-foot-publish,
.article-box-foot-tag {
  display: block;
  height: 100%;
  border: 0;
  float: left;
  text-align: left;
}
.article-box-title-input {
  width: calc(100% - 150px);
  padding-left: 20px;
  font-size: 30px;
}
.article-box-title-input:focus {
  outline: none;
}
.article-box--title-home {
  width: 120px;
  padding-top: 22px;
  text-align: center;
}
.article-box-content {
  width: 100%;
  height: calc(100% - 140px);
}
.article-box-foot {
  width: 100%;
  height: 60px;
}
.article-box-foot-type {
  width: 200px;
  padding-top: 16px;
  padding-left: 10px;
}
.article-box-foot-tag {
  width: calc(100% - 550px);
  padding-top: 22px;
  padding-left: 15px;
}
.article-box-foot-publish {
  width: 300px;
  padding-top: 10px;
  text-align: center;
}
.tag-group {
  margin-bottom: 10px;
  line-height: 32px;
  font-weight: bold;
  font-size: 14px;
  color: #333;
  border-bottom: 1px solid #eee;
}
@media (max-width: 768px) {
  .article-box-title-input,
  .article-box-foot-tag,
  .article-box-foot-type,
  .article-box-foot-publish,
  .article-box--title-home {
    width: 100%;
    text-align: left;
    padding-left: 10px;
  }
}
</style>
  